﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace EpcTagLibrary.Pat
{
    public class GID : Pattern
    {
        public GID(PatternField[] fields, Type type)
            : base(fields, type)
        {
        }

        public override int GetTagBitLength()
        {
            return 96;
        }

        public override string GetScheme()
        {
            return "gid-96";
        }

        public override string GetSchemeName()
        {
            return "gid";
        }

        public PatternField ManagerNumberComponent
        {
            get
            {
                return Fields[0];
            }
        }

        public PatternField ObjectClassNumberComponent
        {
            get
            {
                return Fields[1];
            }
        }

        public PatternField SerialNumberComponent
        {
            get
            {
                return Fields[2];
            }
        }

        public class Factory : PatternFactory
        {
            public override Pattern GetPattern(string patBody, bool isGroupPattern, bool isPureid)
            {
                if (!patBody.StartsWith("gid"))
                {
                    throw new PatternParseException("Specified URI does not match the GID URI for patterns.");
                }

                string[] Fields = patBody.Substring(patBody.IndexOf(":") + 1).Split(new char[1] { '.' });

                if (Fields.Length != 3)
                {
                    throw new PatternParseException("Specified URI does not match the GID URI for patterns.");
                }

                PatternField[] PatFields = new PatternField[3];

                try
                {
                    PatFields[0] = new PatternField(Fields[0],isGroupPattern,28);
                    PatFields[0].Property = typeof(EpcTagLibrary.GID).GetProperty("ManagerNumber");

                    PatFields[1] = new PatternField(Fields[1],isGroupPattern,24);
                    PatFields[1].Property = typeof(EpcTagLibrary.GID).GetProperty("ObjectClassNumber");

                    PatFields[2] = new PatternField(Fields[2],isGroupPattern,36);
                    PatFields[2].Property = typeof(EpcTagLibrary.GID).GetProperty("SerialNumber");
                }
                catch (Exception e)
                {
                    throw new PatternParseException("Error occured setting up pattern component for a field: " + patBody, e);
                }

                GID Result = new GID(PatFields,typeof(EpcTagLibrary.GID));

                return Result;
            }
        }
    }
}
